package info.magnolia.blossom.sample.cv.components;

import info.magnolia.blossom.sample.cv.model.CurriculumVitae;
import info.magnolia.blossom.sample.cv.service.CVService;
import info.magnolia.blossom.sample.cv.util.WebUtil;
import info.magnolia.module.blossom.annotation.TabFactory;
import info.magnolia.module.blossom.annotation.Template;
import info.magnolia.module.blossom.annotation.TemplateDescription;
import info.magnolia.module.blossom.dialog.TabBuilder;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: peterbalazs
 * Date: 3/6/13
 * Time: 12:26 PM
 * To change this template use File | Settings | File Templates.
 */
@Template(title = "Edited CV Saved", id = "blossomSample:components/cvedited")
@TemplateDescription("Edited CV is successfully saved")
@Controller
public class SaveEditedCVComponent {

    /**
     * Class logger.
     */
    private static final Logger logger = Logger.getLogger(SaveEditedCVComponent.class);

    @Autowired
    private CVService cvService;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        CustomDateEditor editor = new CustomDateEditor(new SimpleDateFormat("dd-MM-yyyy"), true);
        binder.registerCustomEditor(Date.class, editor);
        binder.registerCustomEditor(MultipartFile.class, new ByteArrayMultipartFileEditor());
    }

    @RequestMapping(value = "/cvtemplate/editcv-saved")
    public String render(final ModelMap model, @ModelAttribute("cvForm") CurriculumVitae cv, HttpServletRequest request){
        final CurriculumVitae originalCV = cvService.getCV(cv.getId());
        if (originalCV == null) {
            logger.error("No CV with id " + cv.getId() + " to be saved");
            model.put(WebUtil.ERROR_MSG, "CV with ID " + cv.getId() + " not found");
            return WebUtil.ERROR_PAGE_PATH;
        }

        cv.setPath(originalCV.getPath());
        final byte[] uploadedPictureContent = WebUtil.getFileContent(request, WebUtil.PARAM_UPLOAD_PICTURE_PARAM);
        if (uploadedPictureContent != null && uploadedPictureContent.length > 0) {
            cv.setPictureFile(uploadedPictureContent);
            cv.setPictureFileName(WebUtil.getFileName(request, WebUtil.PARAM_UPLOAD_PICTURE_PARAM));
        }

        try {
            cvService.udpateCV(cv);
        } catch (Exception e) {
            logger.error("Error updating CV with id " + cv.getId());
            model.put(WebUtil.ERROR_MSG, "There was an error while updating the CV:<br/>" + e.getMessage());
            return WebUtil.ERROR_PAGE_PATH;
        }

        model.put("cvid", cv.getId());
        model.put("name", cv.getName());
        return "components/editCV-saved.jsp";
    }

    @TabFactory("Settings")
    public void settingsTab(final TabBuilder tab) {
        tab.addUuidLink("viewLink", "View Link", "Link to the view page");
        tab.addUuidLink("addLink", "Add New Link", "Link to the Add New page");
        tab.addUuidLink("listLink", "List Link", "Link to the View All CVs page");
    }
}
